package com.cloudweb.oa.filter;

import com.alibaba.fastjson.JSONObject;
import com.cloudweb.oa.util.AuthUtil;
import com.redmoon.oa.android.Privilege;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.*;
import javax.servlet.FilterConfig;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

@Slf4j
@WebFilter(urlPatterns="/public/app",filterName="authFilter")
public class AuthFilter implements Filter {

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest)request;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        String skey = req.getHeader("skey");
        JSONObject jsonObject = new JSONObject();
        boolean re = false;
        if (null == skey || skey.isEmpty()) {
            jsonObject.put("res", 0);
            jsonObject.put("errCode", "403");
            jsonObject.put("msg", "客户端请求参数中无skey信息");
        } else {
            AuthUtil authUtil = new AuthUtil();
            re = authUtil.auth(req);
            if (!re) {
                jsonObject.put("res", 0);
                jsonObject.put("errCode", authUtil.getErrCode());
                jsonObject.put("errMsg", authUtil.getErrMsg());
            }
            else {
                Privilege privilege = new Privilege();
                privilege.doLogin(req, skey);
            }
        }
        if(!re){
            PrintWriter writer = null;
            OutputStreamWriter osw = null;
            try {
                osw = new OutputStreamWriter(response.getOutputStream() , "UTF-8");
                writer = new PrintWriter(osw, true);
                writer.write(jsonObject.toString());
                writer.flush();
                writer.close();
                osw.close();
            } catch (UnsupportedEncodingException e) {
                log.error(e.getMessage(), e);
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            } finally {
                if (null != writer) {
                    writer.close();
                }
                if(null != osw){
                    osw.close();
                }
            }
            return;
        }

        chain.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
}
